home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / optparse.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  54KB  |  1,530 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''A powerful, extensible, and easy-to-use option parser.
  5.  
  6. By Greg Ward <gward@python.net>
  7.  
  8. Originally distributed as Optik.
  9.  
  10. For support, use the optik-users@lists.sourceforge.net mailing list
  11. (http://lists.sourceforge.net/lists/listinfo/optik-users).
  12.  
  13. Simple usage example:
  14.  
  15.    from optparse import OptionParser
  16.  
  17.    parser = OptionParser()
  18.    parser.add_option("-f", "--file", dest="filename",
  19.                      help="write report to FILE", metavar="FILE")
  20.    parser.add_option("-q", "--quiet",
  21.                      action="store_false", dest="verbose", default=True,
  22.                      help="don\'t print status messages to stdout")
  23.  
  24.    (options, args) = parser.parse_args()
  25. '''
  26. __version__ = '1.5.3'
  27. __all__ = [
  28.     'Option',
  29.     'make_option',
  30.     'SUPPRESS_HELP',
  31.     'SUPPRESS_USAGE',
  32.     'Values',
  33.     'OptionContainer',
  34.     'OptionGroup',
  35.     'OptionParser',
  36.     'HelpFormatter',
  37.     'IndentedHelpFormatter',
  38.     'TitledHelpFormatter',
  39.     'OptParseError',
  40.     'OptionError',
  41.     'OptionConflictError',
  42.     'OptionValueError',
  43.     'BadOptionError']
  44. __copyright__ = '\nCopyright (c) 2001-2006 Gregory P. Ward.  All rights reserved.\nCopyright (c) 2002-2006 Python Software Foundation.  All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n  * Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n\n  * Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n\n  * Neither the name of the author nor the names of its\n    contributors may be used to endorse or promote products derived from\n    this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS\nIS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\nTO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n'
  45. import sys
  46. import os
  47. import types
  48. import textwrap
  49.  
  50. def _repr(self):
  51.     return '<%s at 0x%x: %s>' % (self.__class__.__name__, id(self), self)
  52.  
  53.  
  54. try:
  55.     from gettext import gettext
  56. except ImportError:
  57.     
  58.     def gettext(message):
  59.         return message
  60.  
  61.  
  62. _ = gettext
  63.  
  64. class OptParseError(Exception):
  65.     
  66.     def __init__(self, msg):
  67.         self.msg = msg
  68.  
  69.     
  70.     def __str__(self):
  71.         return self.msg
  72.  
  73.  
  74.  
  75. class OptionError(OptParseError):
  76.     '''
  77.     Raised if an Option instance is created with invalid or
  78.     inconsistent arguments.
  79.     '''
  80.     
  81.     def __init__(self, msg, option):
  82.         self.msg = msg
  83.         self.option_id = str(option)
  84.  
  85.     
  86.     def __str__(self):
  87.         if self.option_id:
  88.             return 'option %s: %s' % (self.option_id, self.msg)
  89.         return self.msg
  90.  
  91.  
  92.  
  93. class OptionConflictError(OptionError):
  94.     '''
  95.     Raised if conflicting options are added to an OptionParser.
  96.     '''
  97.     pass
  98.  
  99.  
  100. class OptionValueError(OptParseError):
  101.     '''
  102.     Raised if an invalid option value is encountered on the command
  103.     line.
  104.     '''
  105.     pass
  106.  
  107.  
  108. class BadOptionError(OptParseError):
  109.     '''
  110.     Raised if an invalid option is seen on the command line.
  111.     '''
  112.     
  113.     def __init__(self, opt_str):
  114.         self.opt_str = opt_str
  115.  
  116.     
  117.     def __str__(self):
  118.         return _('no such option: %s') % self.opt_str
  119.  
  120.  
  121.  
  122. class AmbiguousOptionError(BadOptionError):
  123.     '''
  124.     Raised if an ambiguous option is seen on the command line.
  125.     '''
  126.     
  127.     def __init__(self, opt_str, possibilities):
  128.         BadOptionError.__init__(self, opt_str)
  129.         self.possibilities = possibilities
  130.  
  131.     
  132.     def __str__(self):
  133.         return _('ambiguous option: %s (%s?)') % (self.opt_str, ', '.join(self.possibilities))
  134.  
  135.  
  136.  
  137. class HelpFormatter:
  138.     '''
  139.     Abstract base class for formatting option help.  OptionParser
  140.     instances should use one of the HelpFormatter subclasses for
  141.     formatting help; by default IndentedHelpFormatter is used.
  142.  
  143.     Instance attributes:
  144.       parser : OptionParser
  145.         the controlling OptionParser instance
  146.       indent_increment : int
  147.         the number of columns to indent per nesting level
  148.       max_help_position : int
  149.         the maximum starting column for option help text
  150.       help_position : int
  151.         the calculated starting column for option help text;
  152.         initially the same as the maximum
  153.       width : int
  154.         total number of columns for output (pass None to constructor for
  155.         this value to be taken from the $COLUMNS environment variable)
  156.       level : int
  157.         current indentation level
  158.       current_indent : int
  159.         current indentation level (in columns)
  160.       help_width : int
  161.         number of columns available for option help text (calculated)
  162.       default_tag : str
  163.         text to replace with each option\'s default value, "%default"
  164.         by default.  Set to false value to disable default value expansion.
  165.       option_strings : { Option : str }
  166.         maps Option instances to the snippet of help text explaining
  167.         the syntax of that option, e.g. "-h, --help" or
  168.         "-fFILE, --file=FILE"
  169.       _short_opt_fmt : str
  170.         format string controlling how short options with values are
  171.         printed in help text.  Must be either "%s%s" ("-fFILE") or
  172.         "%s %s" ("-f FILE"), because those are the two syntaxes that
  173.         Optik supports.
  174.       _long_opt_fmt : str
  175.         similar but for long options; must be either "%s %s" ("--file FILE")
  176.         or "%s=%s" ("--file=FILE").
  177.     '''
  178.     NO_DEFAULT_VALUE = 'none'
  179.     
  180.     def __init__(self, indent_increment, max_help_position, width, short_first):
  181.         self.parser = None
  182.         self.indent_increment = indent_increment
  183.         self.help_position = self.max_help_position = max_help_position
  184.         if width is None:
  185.             
  186.             try:
  187.                 width = int(os.environ['COLUMNS'])
  188.             except (KeyError, ValueError):
  189.                 width = 80
  190.  
  191.             width -= 2
  192.         
  193.         self.width = width
  194.         self.current_indent = 0
  195.         self.level = 0
  196.         self.help_width = None
  197.         self.short_first = short_first
  198.         self.default_tag = '%default'
  199.         self.option_strings = { }
  200.         self._short_opt_fmt = '%s %s'
  201.         self._long_opt_fmt = '%s=%s'
  202.  
  203.     
  204.     def set_parser(self, parser):
  205.         self.parser = parser
  206.  
  207.     
  208.     def set_short_opt_delimiter(self, delim):
  209.         if delim not in ('', ' '):
  210.             raise ValueError('invalid metavar delimiter for short options: %r' % delim)
  211.         delim not in ('', ' ')
  212.         self._short_opt_fmt = '%s' + delim + '%s'
  213.  
  214.     
  215.     def set_long_opt_delimiter(self, delim):
  216.         if delim not in ('=', ' '):
  217.             raise ValueError('invalid metavar delimiter for long options: %r' % delim)
  218.         delim not in ('=', ' ')
  219.         self._long_opt_fmt = '%s' + delim + '%s'
  220.  
  221.     
  222.     def indent(self):
  223.         self.current_indent += self.indent_increment
  224.         self.level += 1
  225.  
  226.     
  227.     def dedent(self):
  228.         self.current_indent -= self.indent_increment
  229.         if not self.current_indent >= 0:
  230.             raise AssertionError, 'Indent decreased below 0.'
  231.         self.level -= 1
  232.  
  233.     
  234.     def format_usage(self, usage):
  235.         raise NotImplementedError, 'subclasses must implement'
  236.  
  237.     
  238.     def format_heading(self, heading):
  239.         raise NotImplementedError, 'subclasses must implement'
  240.  
  241.     
  242.     def _format_text(self, text):
  243.         '''
  244.         Format a paragraph of free-form text for inclusion in the
  245.         help output at the current indentation level.
  246.         '''
  247.         text_width = self.width - self.current_indent
  248.         indent = ' ' * self.current_indent
  249.         return textwrap.fill(text, text_width, initial_indent = indent, subsequent_indent = indent)
  250.  
  251.     
  252.     def format_description(self, description):
  253.         if description:
  254.             return self._format_text(description) + '\n'
  255.         return ''
  256.  
  257.     
  258.     def format_epilog(self, epilog):
  259.         if epilog:
  260.             return '\n' + self._format_text(epilog) + '\n'
  261.         return ''
  262.  
  263.     
  264.     def expand_default(self, option):
  265.         if self.parser is None or not (self.default_tag):
  266.             return option.help
  267.         default_value = self.parser.defaults.get(option.dest)
  268.         if default_value is NO_DEFAULT or default_value is None:
  269.             default_value = self.NO_DEFAULT_VALUE
  270.         
  271.         return option.help.replace(self.default_tag, str(default_value))
  272.  
  273.     
  274.     def format_option(self, option):
  275.         result = []
  276.         opts = self.option_strings[option]
  277.         opt_width = self.help_position - self.current_indent - 2
  278.         if len(opts) > opt_width:
  279.             opts = '%*s%s\n' % (self.current_indent, '', opts)
  280.             indent_first = self.help_position
  281.         else:
  282.             opts = '%*s%-*s  ' % (self.current_indent, '', opt_width, opts)
  283.             indent_first = 0
  284.         result.append(opts)
  285.         if option.help:
  286.             help_text = self.expand_default(option)
  287.             help_lines = textwrap.wrap(help_text, self.help_width)
  288.             result.append('%*s%s\n' % (indent_first, '', help_lines[0]))
  289.             []([ '%*s%s\n' % (self.help_position, '', line) for line in help_lines[1:] ])
  290.         elif opts[-1] != '\n':
  291.             result.append('\n')
  292.         
  293.         return ''.join(result)
  294.  
  295.     
  296.     def store_option_strings(self, parser):
  297.         self.indent()
  298.         max_len = 0
  299.         for opt in parser.option_list:
  300.             strings = self.format_option_strings(opt)
  301.             self.option_strings[opt] = strings
  302.             max_len = max(max_len, len(strings) + self.current_indent)
  303.         
  304.         self.indent()
  305.         for group in parser.option_groups:
  306.             for opt in group.option_list:
  307.                 strings = self.format_option_strings(opt)
  308.                 self.option_strings[opt] = strings
  309.                 max_len = max(max_len, len(strings) + self.current_indent)
  310.             
  311.         
  312.         self.dedent()
  313.         self.dedent()
  314.         self.help_position = min(max_len + 2, self.max_help_position)
  315.         self.help_width = self.width - self.help_position
  316.  
  317.     
  318.     def format_option_strings(self, option):
  319.         '''Return a comma-separated list of option strings & metavariables.'''
  320.         return ', '.join(opts)
  321.  
  322.  
  323.  
  324. class IndentedHelpFormatter(HelpFormatter):
  325.     '''Format help with indented section bodies.
  326.     '''
  327.     
  328.     def __init__(self, indent_increment = 2, max_help_position = 24, width = None, short_first = 1):
  329.         HelpFormatter.__init__(self, indent_increment, max_help_position, width, short_first)
  330.  
  331.     
  332.     def format_usage(self, usage):
  333.         return _('Usage: %s\n') % usage
  334.  
  335.     
  336.     def format_heading(self, heading):
  337.         return '%*s%s:\n' % (self.current_indent, '', heading)
  338.  
  339.  
  340.  
  341. class TitledHelpFormatter(HelpFormatter):
  342.     '''Format help with underlined section headers.
  343.     '''
  344.     
  345.     def __init__(self, indent_increment = 0, max_help_position = 24, width = None, short_first = 0):
  346.         HelpFormatter.__init__(self, indent_increment, max_help_position, width, short_first)
  347.  
  348.     
  349.     def format_usage(self, usage):
  350.         return '%s  %s\n' % (self.format_heading(_('Usage')), usage)
  351.  
  352.     
  353.     def format_heading(self, heading):
  354.         return '%s\n%s\n' % (heading, '=-'[self.level] * len(heading))
  355.  
  356.  
  357.  
  358. def _parse_num(val, type):
  359.     if val[:2].lower() == '0x':
  360.         radix = 16
  361.     elif val[:2].lower() == '0b':
  362.         radix = 2
  363.         if not val[2:]:
  364.             pass
  365.         val = '0'
  366.     elif val[:1] == '0':
  367.         radix = 8
  368.     else:
  369.         radix = 10
  370.     return type(val, radix)
  371.  
  372.  
  373. def _parse_int(val):
  374.     return _parse_num(val, int)
  375.  
  376.  
  377. def _parse_long(val):
  378.     return _parse_num(val, long)
  379.  
  380. _builtin_cvt = {
  381.     'int': (_parse_int, _('integer')),
  382.     'long': (_parse_long, _('long integer')),
  383.     'float': (float, _('floating-point')),
  384.     'complex': (complex, _('complex')) }
  385.  
  386. def check_builtin(option, opt, value):
  387.     (cvt, what) = _builtin_cvt[option.type]
  388.     
  389.     try:
  390.         return cvt(value)
  391.     except ValueError:
  392.         raise OptionValueError(_('option %s: invalid %s value: %r') % (opt, what, value))
  393.  
  394.  
  395.  
  396. def check_choice(option, opt, value):
  397.     if value in option.choices:
  398.         return value
  399.     choices = ', '.join(map(repr, option.choices))
  400.     raise OptionValueError(_('option %s: invalid choice: %r (choose from %s)') % (opt, value, choices))
  401.  
  402. NO_DEFAULT = ('NO', 'DEFAULT')
  403.  
  404. class Option:
  405.     '''
  406.     Instance attributes:
  407.       _short_opts : [string]
  408.       _long_opts : [string]
  409.  
  410.       action : string
  411.       type : string
  412.       dest : string
  413.       default : any
  414.       nargs : int
  415.       const : any
  416.       choices : [string]
  417.       callback : function
  418.       callback_args : (any*)
  419.       callback_kwargs : { string : any }
  420.       help : string
  421.       metavar : string
  422.     '''
  423.     ATTRS = [
  424.         'action',
  425.         'type',
  426.         'dest',
  427.         'default',
  428.         'nargs',
  429.         'const',
  430.         'choices',
  431.         'callback',
  432.         'callback_args',
  433.         'callback_kwargs',
  434.         'help',
  435.         'metavar']
  436.     ACTIONS = ('store', 'store_const', 'store_true', 'store_false', 'append', 'append_const', 'count', 'callback', 'help', 'version')
  437.     STORE_ACTIONS = ('store', 'store_const', 'store_true', 'store_false', 'append', 'append_const', 'count')
  438.     TYPED_ACTIONS = ('store', 'append', 'callback')
  439.     ALWAYS_TYPED_ACTIONS = ('store', 'append')
  440.     CONST_ACTIONS = ('store_const', 'append_const')
  441.     TYPES = ('string', 'int', 'long', 'float', 'complex', 'choice')
  442.     TYPE_CHECKER = {
  443.         'int': check_builtin,
  444.         'long': check_builtin,
  445.         'float': check_builtin,
  446.         'complex': check_builtin,
  447.         'choice': check_choice }
  448.     CHECK_METHODS = None
  449.     
  450.     def __init__(self, *opts, **attrs):
  451.         self._short_opts = []
  452.         self._long_opts = []
  453.         opts = self._check_opt_strings(opts)
  454.         self._set_opt_strings(opts)
  455.         self._set_attrs(attrs)
  456.         for checker in self.CHECK_METHODS:
  457.             checker(self)
  458.         
  459.  
  460.     
  461.     def _check_opt_strings(self, opts):
  462.         opts = filter(None, opts)
  463.         if not opts:
  464.             raise TypeError('at least one option string must be supplied')
  465.         opts
  466.         return opts
  467.  
  468.     
  469.     def _set_opt_strings(self, opts):
  470.         for opt in opts:
  471.             if len(opt) < 2:
  472.                 raise OptionError('invalid option string %r: must be at least two characters long' % opt, self)
  473.             len(opt) < 2
  474.             if len(opt) == 2:
  475.                 if not opt[0] == '-' and opt[1] != '-':
  476.                     raise OptionError('invalid short option string %r: must be of the form -x, (x any non-dash char)' % opt, self)
  477.                 opt[1] != '-'
  478.                 self._short_opts.append(opt)
  479.                 continue
  480.             if not opt[0:2] == '--' and opt[2] != '-':
  481.                 raise OptionError('invalid long option string %r: must start with --, followed by non-dash' % opt, self)
  482.             opt[2] != '-'
  483.             self._long_opts.append(opt)
  484.         
  485.  
  486.     
  487.     def _set_attrs(self, attrs):
  488.         for attr in self.ATTRS:
  489.             if attr in attrs:
  490.                 setattr(self, attr, attrs[attr])
  491.                 del attrs[attr]
  492.                 continue
  493.             if attr == 'default':
  494.                 setattr(self, attr, NO_DEFAULT)
  495.                 continue
  496.             setattr(self, attr, None)
  497.         
  498.         if attrs:
  499.             attrs = attrs.keys()
  500.             attrs.sort()
  501.             raise OptionError('invalid keyword arguments: %s' % ', '.join(attrs), self)
  502.         attrs
  503.  
  504.     
  505.     def _check_action(self):
  506.         if self.action is None:
  507.             self.action = 'store'
  508.         elif self.action not in self.ACTIONS:
  509.             raise OptionError('invalid action: %r' % self.action, self)
  510.         
  511.  
  512.     
  513.     def _check_type(self):
  514.         if self.type is None:
  515.             if self.action in self.ALWAYS_TYPED_ACTIONS:
  516.                 if self.choices is not None:
  517.                     self.type = 'choice'
  518.                 else:
  519.                     self.type = 'string'
  520.             
  521.         else:
  522.             import __builtin__ as __builtin__
  523.             if (type(self.type) is types.TypeType or hasattr(self.type, '__name__')) and getattr(__builtin__, self.type.__name__, None) is self.type:
  524.                 self.type = self.type.__name__
  525.             
  526.             if self.type == 'str':
  527.                 self.type = 'string'
  528.             
  529.             if self.type not in self.TYPES:
  530.                 raise OptionError('invalid option type: %r' % self.type, self)
  531.             self.type not in self.TYPES
  532.             if self.action not in self.TYPED_ACTIONS:
  533.                 raise OptionError('must not supply a type for action %r' % self.action, self)
  534.             self.action not in self.TYPED_ACTIONS
  535.  
  536.     
  537.     def _check_choice(self):
  538.         if self.type == 'choice':
  539.             if self.choices is None:
  540.                 raise OptionError("must supply a list of choices for type 'choice'", self)
  541.             self.choices is None
  542.             if type(self.choices) not in (types.TupleType, types.ListType):
  543.                 raise OptionError("choices must be a list of strings ('%s' supplied)" % str(type(self.choices)).split("'")[1], self)
  544.             type(self.choices) not in (types.TupleType, types.ListType)
  545.         elif self.choices is not None:
  546.             raise OptionError('must not supply choices for type %r' % self.type, self)
  547.         
  548.  
  549.     
  550.     def _check_dest(self):
  551.         if not self.action in self.STORE_ACTIONS:
  552.             pass
  553.         takes_value = self.type is not None
  554.         if self.dest is None and takes_value:
  555.             if self._long_opts:
  556.                 self.dest = self._long_opts[0][2:].replace('-', '_')
  557.             else:
  558.                 self.dest = self._short_opts[0][1]
  559.         
  560.  
  561.     
  562.     def _check_const(self):
  563.         if self.action not in self.CONST_ACTIONS and self.const is not None:
  564.             raise OptionError("'const' must not be supplied for action %r" % self.action, self)
  565.         self.const is not None
  566.  
  567.     
  568.     def _check_nargs(self):
  569.         if self.action in self.TYPED_ACTIONS:
  570.             if self.nargs is None:
  571.                 self.nargs = 1
  572.             
  573.         elif self.nargs is not None:
  574.             raise OptionError("'nargs' must not be supplied for action %r" % self.action, self)
  575.         
  576.  
  577.     
  578.     def _check_callback(self):
  579.         if self.action == 'callback':
  580.             if not hasattr(self.callback, '__call__'):
  581.                 raise OptionError('callback not callable: %r' % self.callback, self)
  582.             hasattr(self.callback, '__call__')
  583.             if self.callback_args is not None and type(self.callback_args) is not types.TupleType:
  584.                 raise OptionError('callback_args, if supplied, must be a tuple: not %r' % self.callback_args, self)
  585.             type(self.callback_args) is not types.TupleType
  586.             if self.callback_kwargs is not None and type(self.callback_kwargs) is not types.DictType:
  587.                 raise OptionError('callback_kwargs, if supplied, must be a dict: not %r' % self.callback_kwargs, self)
  588.             type(self.callback_kwargs) is not types.DictType
  589.         elif self.callback is not None:
  590.             raise OptionError('callback supplied (%r) for non-callback option' % self.callback, self)
  591.         
  592.         if self.callback_args is not None:
  593.             raise OptionError('callback_args supplied for non-callback option', self)
  594.         self.callback_args is not None
  595.         if self.callback_kwargs is not None:
  596.             raise OptionError('callback_kwargs supplied for non-callback option', self)
  597.         self.callback_kwargs is not None
  598.  
  599.     CHECK_METHODS = [
  600.         _check_action,
  601.         _check_type,
  602.         _check_choice,
  603.         _check_dest,
  604.         _check_const,
  605.         _check_nargs,
  606.         _check_callback]
  607.     
  608.     def __str__(self):
  609.         return '/'.join(self._short_opts + self._long_opts)
  610.  
  611.     __repr__ = _repr
  612.     
  613.     def takes_value(self):
  614.         return self.type is not None
  615.  
  616.     
  617.     def get_opt_string(self):
  618.         if self._long_opts:
  619.             return self._long_opts[0]
  620.         return self._short_opts[0]
  621.  
  622.     
  623.     def check_value(self, opt, value):
  624.         checker = self.TYPE_CHECKER.get(self.type)
  625.         if checker is None:
  626.             return value
  627.         return checker(self, opt, value)
  628.  
  629.     
  630.     def convert_value(self, opt, value):
  631.         if value is not None:
  632.             if self.nargs == 1:
  633.                 return self.check_value(opt, value)
  634.             return []([ self.check_value(opt, v) for v in value ])
  635.         value is not None
  636.  
  637.     
  638.     def process(self, opt, value, values, parser):
  639.         value = self.convert_value(opt, value)
  640.         return self.take_action(self.action, self.dest, opt, value, values, parser)
  641.  
  642.     
  643.     def take_action(self, action, dest, opt, value, values, parser):
  644.         if action == 'store':
  645.             setattr(values, dest, value)
  646.         elif action == 'store_const':
  647.             setattr(values, dest, self.const)
  648.         elif action == 'store_true':
  649.             setattr(values, dest, True)
  650.         elif action == 'store_false':
  651.             setattr(values, dest, False)
  652.         elif action == 'append':
  653.             values.ensure_value(dest, []).append(value)
  654.         elif action == 'append_const':
  655.             values.ensure_value(dest, []).append(self.const)
  656.         elif action == 'count':
  657.             setattr(values, dest, values.ensure_value(dest, 0) + 1)
  658.         elif action == 'callback':
  659.             if not self.callback_args:
  660.                 pass
  661.             args = ()
  662.             if not self.callback_kwargs:
  663.                 pass
  664.             kwargs = { }
  665.             self.callback(self, opt, value, parser, *args, **kwargs)
  666.         elif action == 'help':
  667.             parser.print_help()
  668.             parser.exit()
  669.         elif action == 'version':
  670.             parser.print_version()
  671.             parser.exit()
  672.         else:
  673.             raise RuntimeError, 'unknown action %r' % self.action
  674.         return action == 'store'
  675.  
  676.  
  677. SUPPRESS_HELP = 'SUPPRESS' + 'HELP'
  678. SUPPRESS_USAGE = 'SUPPRESS' + 'USAGE'
  679.  
  680. try:
  681.     basestring
  682. except NameError:
  683.     
  684.     def isbasestring(x):
  685.         return isinstance(x, (types.StringType, types.UnicodeType))
  686.  
  687.  
  688.  
  689. def isbasestring(x):
  690.     return isinstance(x, basestring)
  691.  
  692.  
  693. class Values:
  694.     
  695.     def __init__(self, defaults = None):
  696.         if defaults:
  697.             for attr, val in defaults.items():
  698.                 setattr(self, attr, val)
  699.             
  700.         
  701.  
  702.     
  703.     def __str__(self):
  704.         return str(self.__dict__)
  705.  
  706.     __repr__ = _repr
  707.     
  708.     def __cmp__(self, other):
  709.         if isinstance(other, Values):
  710.             return cmp(self.__dict__, other.__dict__)
  711.         if isinstance(other, types.DictType):
  712.             return cmp(self.__dict__, other)
  713.         return -1
  714.  
  715.     
  716.     def _update_careful(self, dict):
  717.         '''
  718.         Update the option values from an arbitrary dictionary, but only
  719.         use keys from dict that already have a corresponding attribute
  720.         in self.  Any keys in dict without a corresponding attribute
  721.         are silently ignored.
  722.         '''
  723.         for attr in dir(self):
  724.             if attr in dict:
  725.                 dval = dict[attr]
  726.                 if dval is not None:
  727.                     setattr(self, attr, dval)
  728.                 
  729.             dval is not None
  730.         
  731.  
  732.     
  733.     def _update_loose(self, dict):
  734.         '''
  735.         Update the option values from an arbitrary dictionary,
  736.         using all keys from the dictionary regardless of whether
  737.         they have a corresponding attribute in self or not.
  738.         '''
  739.         self.__dict__.update(dict)
  740.  
  741.     
  742.     def _update(self, dict, mode):
  743.         if mode == 'careful':
  744.             self._update_careful(dict)
  745.         elif mode == 'loose':
  746.             self._update_loose(dict)
  747.         else:
  748.             raise ValueError, 'invalid update mode: %r' % mode
  749.         return mode == 'careful'
  750.  
  751.     
  752.     def read_module(self, modname, mode = 'careful'):
  753.         __import__(modname)
  754.         mod = sys.modules[modname]
  755.         self._update(vars(mod), mode)
  756.  
  757.     
  758.     def read_file(self, filename, mode = 'careful'):
  759.         vars = { }
  760.         execfile(filename, vars)
  761.         self._update(vars, mode)
  762.  
  763.     
  764.     def ensure_value(self, attr, value):
  765.         if not hasattr(self, attr) or getattr(self, attr) is None:
  766.             setattr(self, attr, value)
  767.         
  768.         return getattr(self, attr)
  769.  
  770.  
  771.  
  772. class OptionContainer:
  773.     '''
  774.     Abstract base class.
  775.  
  776.     Class attributes:
  777.       standard_option_list : [Option]
  778.         list of standard options that will be accepted by all instances
  779.         of this parser class (intended to be overridden by subclasses).
  780.  
  781.     Instance attributes:
  782.       option_list : [Option]
  783.         the list of Option objects contained by this OptionContainer
  784.       _short_opt : { string : Option }
  785.         dictionary mapping short option strings, eg. "-f" or "-X",
  786.         to the Option instances that implement them.  If an Option
  787.         has multiple short option strings, it will appears in this
  788.         dictionary multiple times. [1]
  789.       _long_opt : { string : Option }
  790.         dictionary mapping long option strings, eg. "--file" or
  791.         "--exclude", to the Option instances that implement them.
  792.         Again, a given Option can occur multiple times in this
  793.         dictionary. [1]
  794.       defaults : { string : any }
  795.         dictionary mapping option destination names to default
  796.         values for each destination [1]
  797.  
  798.     [1] These mappings are common to (shared by) all components of the
  799.         controlling OptionParser, where they are initially created.
  800.  
  801.     '''
  802.     
  803.     def __init__(self, option_class, conflict_handler, description):
  804.         self._create_option_list()
  805.         self.option_class = option_class
  806.         self.set_conflict_handler(conflict_handler)
  807.         self.set_description(description)
  808.  
  809.     
  810.     def _create_option_mappings(self):
  811.         self._short_opt = { }
  812.         self._long_opt = { }
  813.         self.defaults = { }
  814.  
  815.     
  816.     def _share_option_mappings(self, parser):
  817.         self._short_opt = parser._short_opt
  818.         self._long_opt = parser._long_opt
  819.         self.defaults = parser.defaults
  820.  
  821.     
  822.     def set_conflict_handler(self, handler):
  823.         if handler not in ('error', 'resolve'):
  824.             raise ValueError, 'invalid conflict_resolution value %r' % handler
  825.         handler not in ('error', 'resolve')
  826.         self.conflict_handler = handler
  827.  
  828.     
  829.     def set_description(self, description):
  830.         self.description = description
  831.  
  832.     
  833.     def get_description(self):
  834.         return self.description
  835.  
  836.     
  837.     def destroy(self):
  838.         '''see OptionParser.destroy().'''
  839.         del self._short_opt
  840.         del self._long_opt
  841.         del self.defaults
  842.  
  843.     
  844.     def _check_conflict(self, option):
  845.         conflict_opts = []
  846.         for opt in option._short_opts:
  847.             if opt in self._short_opt:
  848.                 conflict_opts.append((opt, self._short_opt[opt]))
  849.                 continue
  850.         
  851.         for opt in option._long_opts:
  852.             if opt in self._long_opt:
  853.                 conflict_opts.append((opt, self._long_opt[opt]))
  854.                 continue
  855.         
  856.         if conflict_opts:
  857.             handler = self.conflict_handler
  858.             if handler == 'error':
  859.                 raise ', '.join([] % []([ co[0] for co in conflict_opts ]), option)
  860.             handler == 'error'
  861.             if handler == 'resolve':
  862.                 for opt, c_option in conflict_opts:
  863.                     if opt.startswith('--'):
  864.                         c_option._long_opts.remove(opt)
  865.                         del self._long_opt[opt]
  866.                     else:
  867.                         c_option._short_opts.remove(opt)
  868.                         del self._short_opt[opt]
  869.                     if not c_option._short_opts or c_option._long_opts:
  870.                         c_option.container.option_list.remove(c_option)
  871.                         continue
  872.                 
  873.             
  874.         
  875.  
  876.     
  877.     def add_option(self, *args, **kwargs):
  878.         '''add_option(Option)
  879.            add_option(opt_str, ..., kwarg=val, ...)
  880.         '''
  881.         if type(args[0]) in types.StringTypes:
  882.             option = self.option_class(*args, **kwargs)
  883.         elif len(args) == 1 and not kwargs:
  884.             option = args[0]
  885.             if not isinstance(option, Option):
  886.                 raise TypeError, 'not an Option instance: %r' % option
  887.             isinstance(option, Option)
  888.         else:
  889.             raise TypeError, 'invalid arguments'
  890.         (not kwargs)._check_conflict(option)
  891.         self.option_list.append(option)
  892.         option.container = self
  893.         for opt in option._short_opts:
  894.             self._short_opt[opt] = option
  895.         
  896.         for opt in option._long_opts:
  897.             self._long_opt[opt] = option
  898.         
  899.         if option.dest is not None:
  900.             if option.default is not NO_DEFAULT:
  901.                 self.defaults[option.dest] = option.default
  902.             elif option.dest not in self.defaults:
  903.                 self.defaults[option.dest] = None
  904.             
  905.         
  906.         return option
  907.  
  908.     
  909.     def add_options(self, option_list):
  910.         for option in option_list:
  911.             self.add_option(option)
  912.         
  913.  
  914.     
  915.     def get_option(self, opt_str):
  916.         if not self._short_opt.get(opt_str):
  917.             pass
  918.         return self._long_opt.get(opt_str)
  919.  
  920.     
  921.     def has_option(self, opt_str):
  922.         if not opt_str in self._short_opt:
  923.             pass
  924.         return opt_str in self._long_opt
  925.  
  926.     
  927.     def remove_option(self, opt_str):
  928.         option = self._short_opt.get(opt_str)
  929.         if option is None:
  930.             option = self._long_opt.get(opt_str)
  931.         
  932.         if option is None:
  933.             raise ValueError('no such option %r' % opt_str)
  934.         option is None
  935.         for opt in option._short_opts:
  936.             del self._short_opt[opt]
  937.         
  938.         for opt in option._long_opts:
  939.             del self._long_opt[opt]
  940.         
  941.         option.container.option_list.remove(option)
  942.  
  943.     
  944.     def format_option_help(self, formatter):
  945.         if not self.option_list:
  946.             return ''
  947.         result = []
  948.         for option in self.option_list:
  949.             if option.help is not SUPPRESS_HELP:
  950.                 result.append(formatter.format_option(option))
  951.                 continue
  952.             self.option_list
  953.         
  954.         return ''.join(result)
  955.  
  956.     
  957.     def format_description(self, formatter):
  958.         return formatter.format_description(self.get_description())
  959.  
  960.     
  961.     def format_help(self, formatter):
  962.         result = []
  963.         if self.description:
  964.             result.append(self.format_description(formatter))
  965.         
  966.         if self.option_list:
  967.             result.append(self.format_option_help(formatter))
  968.         
  969.         return '\n'.join(result)
  970.  
  971.  
  972.  
  973. class OptionGroup(OptionContainer):
  974.     
  975.     def __init__(self, parser, title, description = None):
  976.         self.parser = parser
  977.         OptionContainer.__init__(self, parser.option_class, parser.conflict_handler, description)
  978.         self.title = title
  979.  
  980.     
  981.     def _create_option_list(self):
  982.         self.option_list = []
  983.         self._share_option_mappings(self.parser)
  984.  
  985.     
  986.     def set_title(self, title):
  987.         self.title = title
  988.  
  989.     
  990.     def destroy(self):
  991.         '''see OptionParser.destroy().'''
  992.         OptionContainer.destroy(self)
  993.         del self.option_list
  994.  
  995.     
  996.     def format_help(self, formatter):
  997.         result = formatter.format_heading(self.title)
  998.         formatter.indent()
  999.         result += OptionContainer.format_help(self, formatter)
  1000.         formatter.dedent()
  1001.         return result
  1002.  
  1003.  
  1004.  
  1005. class OptionParser(OptionContainer):
  1006.     '''
  1007.     Class attributes:
  1008.       standard_option_list : [Option]
  1009.         list of standard options that will be accepted by all instances
  1010.         of this parser class (intended to be overridden by subclasses).
  1011.  
  1012.     Instance attributes:
  1013.       usage : string
  1014.         a usage string for your program.  Before it is displayed
  1015.         to the user, "%prog" will be expanded to the name of
  1016.         your program (self.prog or os.path.basename(sys.argv[0])).
  1017.       prog : string
  1018.         the name of the current program (to override
  1019.         os.path.basename(sys.argv[0])).
  1020.       epilog : string
  1021.         paragraph of help text to print after option help
  1022.  
  1023.       option_groups : [OptionGroup]
  1024.         list of option groups in this parser (option groups are
  1025.         irrelevant for parsing the command-line, but very useful
  1026.         for generating help)
  1027.  
  1028.       allow_interspersed_args : bool = true
  1029.         if true, positional arguments may be interspersed with options.
  1030.         Assuming -a and -b each take a single argument, the command-line
  1031.           -ablah foo bar -bboo baz
  1032.         will be interpreted the same as
  1033.           -ablah -bboo -- foo bar baz
  1034.         If this flag were false, that command line would be interpreted as
  1035.           -ablah -- foo bar -bboo baz
  1036.         -- ie. we stop processing options as soon as we see the first
  1037.         non-option argument.  (This is the tradition followed by
  1038.         Python\'s getopt module, Perl\'s Getopt::Std, and other argument-
  1039.         parsing libraries, but it is generally annoying to users.)
  1040.  
  1041.       process_default_values : bool = true
  1042.         if true, option default values are processed similarly to option
  1043.         values from the command line: that is, they are passed to the
  1044.         type-checking function for the option\'s type (as long as the
  1045.         default value is a string).  (This really only matters if you
  1046.         have defined custom types; see SF bug #955889.)  Set it to false
  1047.         to restore the behaviour of Optik 1.4.1 and earlier.
  1048.  
  1049.       rargs : [string]
  1050.         the argument list currently being parsed.  Only set when
  1051.         parse_args() is active, and continually trimmed down as
  1052.         we consume arguments.  Mainly there for the benefit of
  1053.         callback options.
  1054.       largs : [string]
  1055.         the list of leftover arguments that we have skipped while
  1056.         parsing options.  If allow_interspersed_args is false, this
  1057.         list is always empty.
  1058.       values : Values
  1059.         the set of option values currently being accumulated.  Only
  1060.         set when parse_args() is active.  Also mainly for callbacks.
  1061.  
  1062.     Because of the \'rargs\', \'largs\', and \'values\' attributes,
  1063.     OptionParser is not thread-safe.  If, for some perverse reason, you
  1064.     need to parse command-line arguments simultaneously in different
  1065.     threads, use different OptionParser instances.
  1066.  
  1067.     '''
  1068.     standard_option_list = []
  1069.     
  1070.     def __init__(self, usage = None, option_list = None, option_class = Option, version = None, conflict_handler = 'error', description = None, formatter = None, add_help_option = True, prog = None, epilog = None):
  1071.         OptionContainer.__init__(self, option_class, conflict_handler, description)
  1072.         self.set_usage(usage)
  1073.         self.prog = prog
  1074.         self.version = version
  1075.         self.allow_interspersed_args = True
  1076.         self.process_default_values = True
  1077.         if formatter is None:
  1078.             formatter = IndentedHelpFormatter()
  1079.         
  1080.         self.formatter = formatter
  1081.         self.formatter.set_parser(self)
  1082.         self.epilog = epilog
  1083.         self._populate_option_list(option_list, add_help = add_help_option)
  1084.         self._init_parsing_state()
  1085.  
  1086.     
  1087.     def destroy(self):
  1088.         '''
  1089.         Declare that you are done with this OptionParser.  This cleans up
  1090.         reference cycles so the OptionParser (and all objects referenced by
  1091.         it) can be garbage-collected promptly.  After calling destroy(), the
  1092.         OptionParser is unusable.
  1093.         '''
  1094.         OptionContainer.destroy(self)
  1095.         for group in self.option_groups:
  1096.             group.destroy()
  1097.         
  1098.         del self.option_list
  1099.         del self.option_groups
  1100.         del self.formatter
  1101.  
  1102.     
  1103.     def _create_option_list(self):
  1104.         self.option_list = []
  1105.         self.option_groups = []
  1106.         self._create_option_mappings()
  1107.  
  1108.     
  1109.     def _add_help_option(self):
  1110.         self.add_option('-h', '--help', action = 'help', help = _('show this help message and exit'))
  1111.  
  1112.     
  1113.     def _add_version_option(self):
  1114.         self.add_option('--version', action = 'version', help = _("show program's version number and exit"))
  1115.  
  1116.     
  1117.     def _populate_option_list(self, option_list, add_help = True):
  1118.         if self.standard_option_list:
  1119.             self.add_options(self.standard_option_list)
  1120.         
  1121.         if option_list:
  1122.             self.add_options(option_list)
  1123.         
  1124.         if self.version:
  1125.             self._add_version_option()
  1126.         
  1127.         if add_help:
  1128.             self._add_help_option()
  1129.         
  1130.  
  1131.     
  1132.     def _init_parsing_state(self):
  1133.         self.rargs = None
  1134.         self.largs = None
  1135.         self.values = None
  1136.  
  1137.     
  1138.     def set_usage(self, usage):
  1139.         if usage is None:
  1140.             self.usage = _('%prog [options]')
  1141.         elif usage is SUPPRESS_USAGE:
  1142.             self.usage = None
  1143.         elif usage.lower().startswith('usage: '):
  1144.             self.usage = usage[7:]
  1145.         else:
  1146.             self.usage = usage
  1147.  
  1148.     
  1149.     def enable_interspersed_args(self):
  1150.         '''Set parsing to not stop on the first non-option, allowing
  1151.         interspersing switches with command arguments. This is the
  1152.         default behavior. See also disable_interspersed_args() and the
  1153.         class documentation description of the attribute
  1154.         allow_interspersed_args.'''
  1155.         self.allow_interspersed_args = True
  1156.  
  1157.     
  1158.     def disable_interspersed_args(self):
  1159.         """Set parsing to stop on the first non-option. Use this if
  1160.         you have a command processor which runs another command that
  1161.         has options of its own and you want to make sure these options
  1162.         don't get confused.
  1163.         """
  1164.         self.allow_interspersed_args = False
  1165.  
  1166.     
  1167.     def set_process_default_values(self, process):
  1168.         self.process_default_values = process
  1169.  
  1170.     
  1171.     def set_default(self, dest, value):
  1172.         self.defaults[dest] = value
  1173.  
  1174.     
  1175.     def set_defaults(self, **kwargs):
  1176.         self.defaults.update(kwargs)
  1177.  
  1178.     
  1179.     def _get_all_options(self):
  1180.         options = self.option_list[:]
  1181.         for group in self.option_groups:
  1182.             options.extend(group.option_list)
  1183.         
  1184.         return options
  1185.  
  1186.     
  1187.     def get_default_values(self):
  1188.         if not self.process_default_values:
  1189.             return Values(self.defaults)
  1190.         defaults = self.defaults.copy()
  1191.         for option in self._get_all_options():
  1192.             default = defaults.get(option.dest)
  1193.             if isbasestring(default):
  1194.                 opt_str = option.get_opt_string()
  1195.                 defaults[option.dest] = option.check_value(opt_str, default)
  1196.                 continue
  1197.             self.process_default_values
  1198.         
  1199.         return Values(defaults)
  1200.  
  1201.     
  1202.     def add_option_group(self, *args, **kwargs):
  1203.         if type(args[0]) is types.StringType:
  1204.             group = OptionGroup(self, *args, **kwargs)
  1205.         elif len(args) == 1 and not kwargs:
  1206.             group = args[0]
  1207.             if not isinstance(group, OptionGroup):
  1208.                 raise TypeError, 'not an OptionGroup instance: %r' % group
  1209.             isinstance(group, OptionGroup)
  1210.             if group.parser is not self:
  1211.                 raise ValueError, 'invalid OptionGroup (wrong parser)'
  1212.             group.parser is not self
  1213.         else:
  1214.             raise TypeError, 'invalid arguments'
  1215.         (not kwargs).option_groups.append(group)
  1216.         return group
  1217.  
  1218.     
  1219.     def get_option_group(self, opt_str):
  1220.         if not self._short_opt.get(opt_str):
  1221.             pass
  1222.         option = self._long_opt.get(opt_str)
  1223.         if option and option.container is not self:
  1224.             return option.container
  1225.  
  1226.     
  1227.     def _get_args(self, args):
  1228.         if args is None:
  1229.             return sys.argv[1:]
  1230.         return args[:]
  1231.  
  1232.     
  1233.     def parse_args(self, args = None, values = None):
  1234.         """
  1235.         parse_args(args : [string] = sys.argv[1:],
  1236.                    values : Values = None)
  1237.         -> (values : Values, args : [string])
  1238.  
  1239.         Parse the command-line options found in 'args' (default:
  1240.         sys.argv[1:]).  Any errors result in a call to 'error()', which
  1241.         by default prints the usage message to stderr and calls
  1242.         sys.exit() with an error message.  On success returns a pair
  1243.         (values, args) where 'values' is an Values instance (with all
  1244.         your option values) and 'args' is the list of arguments left
  1245.         over after parsing options.
  1246.         """
  1247.         rargs = self._get_args(args)
  1248.         if values is None:
  1249.             values = self.get_default_values()
  1250.         
  1251.         self.rargs = rargs
  1252.         self.largs = largs = []
  1253.         self.values = values
  1254.         
  1255.         try:
  1256.             stop = self._process_args(largs, rargs, values)
  1257.         except (BadOptionError, OptionValueError):
  1258.             err = None
  1259.             self.error(str(err))
  1260.  
  1261.         args = largs + rargs
  1262.         return self.check_values(values, args)
  1263.  
  1264.     
  1265.     def check_values(self, values, args):
  1266.         '''
  1267.         check_values(values : Values, args : [string])
  1268.         -> (values : Values, args : [string])
  1269.  
  1270.         Check that the supplied option values and leftover arguments are
  1271.         valid.  Returns the option values and leftover arguments
  1272.         (possibly adjusted, possibly completely new -- whatever you
  1273.         like).  Default implementation just returns the passed-in
  1274.         values; subclasses may override as desired.
  1275.         '''
  1276.         return (values, args)
  1277.  
  1278.     
  1279.     def _process_args(self, largs, rargs, values):
  1280.         """_process_args(largs : [string],
  1281.                          rargs : [string],
  1282.                          values : Values)
  1283.  
  1284.         Process command-line arguments and populate 'values', consuming
  1285.         options and arguments from 'rargs'.  If 'allow_interspersed_args' is
  1286.         false, stop at the first non-option argument.  If true, accumulate any
  1287.         interspersed non-option arguments in 'largs'.
  1288.         """
  1289.         while rargs:
  1290.             arg = rargs[0]
  1291.             None if arg == '--' else arg == '--'
  1292.             if arg[:1] == '-' and len(arg) > 1:
  1293.                 self._process_short_opts(rargs, values)
  1294.                 continue
  1295.             if self.allow_interspersed_args:
  1296.                 largs.append(arg)
  1297.                 del rargs[0]
  1298.                 continue
  1299.             return None
  1300.  
  1301.     
  1302.     def _match_long_opt(self, opt):
  1303.         """_match_long_opt(opt : string) -> string
  1304.  
  1305.         Determine which long option string 'opt' matches, ie. which one
  1306.         it is an unambiguous abbrevation for.  Raises BadOptionError if
  1307.         'opt' doesn't unambiguously match any long option string.
  1308.         """
  1309.         return _match_abbrev(opt, self._long_opt)
  1310.  
  1311.     
  1312.     def _process_long_opt(self, rargs, values):
  1313.         arg = rargs.pop(0)
  1314.         if '=' in arg:
  1315.             (opt, next_arg) = arg.split('=', 1)
  1316.             rargs.insert(0, next_arg)
  1317.             had_explicit_value = True
  1318.         else:
  1319.             opt = arg
  1320.             had_explicit_value = False
  1321.         opt = self._match_long_opt(opt)
  1322.         option = self._long_opt[opt]
  1323.         if option.takes_value():
  1324.             nargs = option.nargs
  1325.             if len(rargs) < nargs:
  1326.                 if nargs == 1:
  1327.                     self.error(_('%s option requires an argument') % opt)
  1328.                 else:
  1329.                     self.error(_('%s option requires %d arguments') % (opt, nargs))
  1330.             elif nargs == 1:
  1331.                 value = rargs.pop(0)
  1332.             else:
  1333.                 value = tuple(rargs[0:nargs])
  1334.                 del rargs[0:nargs]
  1335.         elif had_explicit_value:
  1336.             self.error(_('%s option does not take a value') % opt)
  1337.         else:
  1338.             value = None
  1339.         option.process(opt, value, values, self)
  1340.  
  1341.     
  1342.     def _process_short_opts(self, rargs, values):
  1343.         arg = rargs.pop(0)
  1344.         stop = False
  1345.         i = 1
  1346.         for ch in arg[1:]:
  1347.             opt = '-' + ch
  1348.             option = self._short_opt.get(opt)
  1349.             i += 1
  1350.             if not option:
  1351.                 raise BadOptionError(opt)
  1352.             option
  1353.             if option.takes_value():
  1354.                 if i < len(arg):
  1355.                     rargs.insert(0, arg[i:])
  1356.                     stop = True
  1357.                 
  1358.                 nargs = option.nargs
  1359.                 if len(rargs) < nargs:
  1360.                     if nargs == 1:
  1361.                         self.error(_('%s option requires an argument') % opt)
  1362.                     else:
  1363.                         self.error(_('%s option requires %d arguments') % (opt, nargs))
  1364.                 elif nargs == 1:
  1365.                     value = rargs.pop(0)
  1366.                 else:
  1367.                     value = tuple(rargs[0:nargs])
  1368.                     del rargs[0:nargs]
  1369.             else:
  1370.                 value = None
  1371.             option.process(opt, value, values, self)
  1372.             if stop:
  1373.                 break
  1374.                 continue
  1375.         
  1376.  
  1377.     
  1378.     def get_prog_name(self):
  1379.         if self.prog is None:
  1380.             return os.path.basename(sys.argv[0])
  1381.         return self.prog
  1382.  
  1383.     
  1384.     def expand_prog_name(self, s):
  1385.         return s.replace('%prog', self.get_prog_name())
  1386.  
  1387.     
  1388.     def get_description(self):
  1389.         return self.expand_prog_name(self.description)
  1390.  
  1391.     
  1392.     def exit(self, status = 0, msg = None):
  1393.         if msg:
  1394.             sys.stderr.write(msg)
  1395.         
  1396.         sys.exit(status)
  1397.  
  1398.     
  1399.     def error(self, msg):
  1400.         """error(msg : string)
  1401.  
  1402.         Print a usage message incorporating 'msg' to stderr and exit.
  1403.         If you override this in a subclass, it should not return -- it
  1404.         should either exit or raise an exception.
  1405.         """
  1406.         self.print_usage(sys.stderr)
  1407.         self.exit(2, '%s: error: %s\n' % (self.get_prog_name(), msg))
  1408.  
  1409.     
  1410.     def get_usage(self):
  1411.         if self.usage:
  1412.             return self.formatter.format_usage(self.expand_prog_name(self.usage))
  1413.         return ''
  1414.  
  1415.     
  1416.     def print_usage(self, file = None):
  1417.         '''print_usage(file : file = stdout)
  1418.  
  1419.         Print the usage message for the current program (self.usage) to
  1420.         \'file\' (default stdout).  Any occurrence of the string "%prog" in
  1421.         self.usage is replaced with the name of the current program
  1422.         (basename of sys.argv[0]).  Does nothing if self.usage is empty
  1423.         or not defined.
  1424.         '''
  1425.         if self.usage:
  1426.             print >>file, self.get_usage()
  1427.         
  1428.  
  1429.     
  1430.     def get_version(self):
  1431.         if self.version:
  1432.             return self.expand_prog_name(self.version)
  1433.         return ''
  1434.  
  1435.     
  1436.     def print_version(self, file = None):
  1437.         '''print_version(file : file = stdout)
  1438.  
  1439.         Print the version message for this program (self.version) to
  1440.         \'file\' (default stdout).  As with print_usage(), any occurrence
  1441.         of "%prog" in self.version is replaced by the current program\'s
  1442.         name.  Does nothing if self.version is empty or undefined.
  1443.         '''
  1444.         if self.version:
  1445.             print >>file, self.get_version()
  1446.         
  1447.  
  1448.     
  1449.     def format_option_help(self, formatter = None):
  1450.         if formatter is None:
  1451.             formatter = self.formatter
  1452.         
  1453.         formatter.store_option_strings(self)
  1454.         result = []
  1455.         result.append(formatter.format_heading(_('Options')))
  1456.         formatter.indent()
  1457.         if self.option_list:
  1458.             result.append(OptionContainer.format_option_help(self, formatter))
  1459.             result.append('\n')
  1460.         
  1461.         for group in self.option_groups:
  1462.             result.append(group.format_help(formatter))
  1463.             result.append('\n')
  1464.         
  1465.         formatter.dedent()
  1466.         return ''.join(result[:-1])
  1467.  
  1468.     
  1469.     def format_epilog(self, formatter):
  1470.         return formatter.format_epilog(self.epilog)
  1471.  
  1472.     
  1473.     def format_help(self, formatter = None):
  1474.         if formatter is None:
  1475.             formatter = self.formatter
  1476.         
  1477.         result = []
  1478.         if self.usage:
  1479.             result.append(self.get_usage() + '\n')
  1480.         
  1481.         if self.description:
  1482.             result.append(self.format_description(formatter) + '\n')
  1483.         
  1484.         result.append(self.format_option_help(formatter))
  1485.         result.append(self.format_epilog(formatter))
  1486.         return ''.join(result)
  1487.  
  1488.     
  1489.     def _get_encoding(self, file):
  1490.         encoding = getattr(file, 'encoding', None)
  1491.         if not encoding:
  1492.             encoding = sys.getdefaultencoding()
  1493.         
  1494.         return encoding
  1495.  
  1496.     
  1497.     def print_help(self, file = None):
  1498.         """print_help(file : file = stdout)
  1499.  
  1500.         Print an extended help message, listing all options and any
  1501.         help text provided with them, to 'file' (default stdout).
  1502.         """
  1503.         if file is None:
  1504.             file = sys.stdout
  1505.         
  1506.         encoding = self._get_encoding(file)
  1507.         file.write(self.format_help().encode(encoding, 'replace'))
  1508.  
  1509.  
  1510.  
  1511. def _match_abbrev(s, wordmap):
  1512.     """_match_abbrev(s : string, wordmap : {string : Option}) -> string
  1513.  
  1514.     Return the string key in 'wordmap' for which 's' is an unambiguous
  1515.     abbreviation.  If 's' is found to be ambiguous or doesn't match any of
  1516.     'words', raise BadOptionError.
  1517.     """
  1518.     if s in wordmap:
  1519.         return s
  1520.     possibilities = _[1]
  1521.     if len(possibilities) == 1:
  1522.         return possibilities[0]
  1523.     if not possibilities:
  1524.         raise BadOptionError(s)
  1525.     possibilities
  1526.     possibilities.sort()
  1527.     raise AmbiguousOptionError(s, possibilities)
  1528.  
  1529. make_option = Option
  1530.